﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Infrastructure;
using Microsoft.AspNetCore.Http;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;


namespace OpenAuth.App
{
    public class EquipmentInventoryApp : BaseApp<EquipmentInventory>
    {
        private RevelanceManagerApp _revelanceApp;
        private IAuth _auth;

        /// <summary>
        /// 加载列表
        /// </summary>
        public TableData Load(QueryEquipmentInventoryListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }

            var properties = loginContext.GetProperties("EquipmentInventory");

            if (properties == null || properties.Count == 0)
            {
                throw new Exception("当前登录用户没有访问该模块字段的权限，请联系管理员配置");
            }

            List<string> orgIdList = new List<string>(); ;
            if (!string.IsNullOrEmpty(request.orgId))
            {
                var org = loginContext.Orgs.SingleOrDefault(u => u.Id == request.orgId);
                foreach (Org item in loginContext.Orgs)
                {
                    if (item.CascadeId.Contains(org.CascadeId))
                    {
                        orgIdList.Add(item.Id);
                    }
                }
            }
            else
            {
                orgIdList = loginContext.Orgs.Select(u => u.Id).ToList();
            }

            var result = new TableData();

            var objs = UnitWork.Find<EquipmentInventory>(u => orgIdList.Contains(u.OrgId));
            if (!string.IsNullOrEmpty(request.key))
            {
                objs = objs.Where(u => u.Name.Contains(request.key));
            }


            var propertyStr = string.Join(',', properties.Select(u => u.Key));
            result.columnHeaders = properties;
            result.data = objs.OrderByDescending(u => u.CreateTime)
                .Skip((request.page - 1) * request.limit)
                .Take(request.limit).Select($"new ({propertyStr})");
            result.count = objs.Count();
            return result;
        }

        public void Add(EquipmentInventory obj)
        {
            if (UnitWork.IsExist<EquipmentInventory>(u => u.Code == obj.Code))
            {
                throw new Exception("编号重复");
            }
            obj.CreateTime = DateTime.Now;
            Repository.Add(obj);
        }

        public void Update(EquipmentInventory obj)
        {
            if (UnitWork.IsExist<EquipmentInventory>(u => u.Code == obj.Code && u.Id != obj.Id))
            {
                throw new Exception("编号重复");
            }
            UnitWork.Update<EquipmentInventory>(u => u.Id == obj.Id, u => new EquipmentInventory
            {
                Name = obj.Name,
                Code = obj.Code,
                OrgId = obj.OrgId,
                PlaceNumber = obj.PlaceNumber,
                Model = obj.Model,
                Supplier = obj.Supplier
            });
            UnitWork.Save();
        }

        public void ImpotExcelData(IFormFile excelfile)
        {
            string serverPath;
            using (var binaryReader = new BinaryReader(excelfile.OpenReadStream()))
            {
                var fileName = Path.GetFileName(excelfile.FileName);
                var data = binaryReader.ReadBytes((int)excelfile.Length);
                //判断文件是否为空
                if (string.IsNullOrEmpty(fileName))
                {
                    throw new Exception("文件名不能为空");
                }

                //判断文件是否为空
                if (data.Length < 1)
                {
                    throw new Exception("文件不能为空");
                }
                var appSetting = new AppSetting();
                var filePath = appSetting.UploadPath;
                if (string.IsNullOrEmpty(filePath))
                {
                    filePath = AppContext.BaseDirectory;
                }

                var uploadPath = filePath + "/" + "数据导入/";
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                var ext = Path.GetExtension(fileName).ToLower();
                string newName = GenerateId.GenerateOrderNumber() + ext;
                serverPath = uploadPath + newName;
                using (var fs = new FileStream(serverPath, FileMode.Create))
                {
                    fs.Write(data, 0, data.Length);
                    fs.Close();
                }
            }
            var file = new FileInfo(serverPath);
            var sourceDatatable = OfficeHelper.InputEPPlusByExcelToDT(file);
            if (sourceDatatable.Rows.Count == 0)
            {
                throw new Exception("数据不能为空");
            }
            var equips = UnitWork.Find<EquipmentInventory>(null).ToList();
            var orgs = UnitWork.Find<Org>(null).ToList();
            List<string> codeList = new List<string>();
            foreach (DataRow item in sourceDatatable.Rows)
            {
                string name = item["名称"].ToString();
                string code = item["编码"].ToString();
                string orgName = item["所属部门"].ToString();
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(code) || string.IsNullOrEmpty(orgName))
                {
                    throw new Exception("请检查必填数据是否都已填充");
                }
                if (!codeList.Contains(code))
                    codeList.Add(code);
                else
                    throw new Exception($"编码[{code}重复]");
                if (equips.Where(u => u.Code == code).Count() > 0)
                    throw new Exception($"编码[{code}]已存在");
                var org = orgs.Where(u => u.Name == orgName);
                if (org.Count() == 0)
                    throw new Exception($"部门{orgName}不存在");
                EquipmentInventory equipment = new EquipmentInventory();
                equipment.Name = name;
                equipment.Code = code;
                equipment.OrgId = org.First().Id;
                equipment.PlaceNumber = item["位号"].ToString();
                equipment.Model = item["规格型号"].ToString();
                equipment.Supplier = item["供应商"].ToString();
                UnitWork.Add(equipment);
            }
            UnitWork.Save();
        }

        public EquipmentInventoryApp(IUnitWork unitWork, IRepository<EquipmentInventory> repository,
            RevelanceManagerApp app, IAuth auth) : base(unitWork, repository)
        {
            _revelanceApp = app;
            _auth = auth;
        }
    }
}